package logic

import (
	"context"
	"fmt"
	"wangwang/models/cache"
	"wangwang/models/mysql"
	"wangwang/pkg"

	"wangwang/wangwangrpc/internal/svc"
	"wangwang/wangwangrpc/wangwangrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *wangwangrpc.RegisterRequest) (*wangwangrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	get := cache.Rdb.Get(l.ctx, "sendSms"+"register"+in.Mobile)
	if get.Val() != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	var user mysql.User
	user = mysql.User{
		Name:     in.Name,
		Mobile:   in.Mobile,
		Emil:     in.Emil,
		Password: pkg.Md5(in.Password),
	}
	err := mysql.DB.Debug().Create(&user).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}

	//注册成功后删除短信缓存
	cache.Rdb.Del(l.ctx, "sendSms"+"register"+in.Mobile)
	return &wangwangrpc.RegisterResponse{Id: int64(user.ID)}, nil
}
